package com.thirteenClassicsServer.cacheService;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thirteenClassics.dto.CatalogQueryDTO;
import com.thirteenClassics.dto.JdbContentForChapterDTO;
import com.thirteenClassics.entity.CatalogBook;
import com.thirteenClassics.entity.Picture;
import com.thirteenClassics.vo.PictureVO;
import com.thirteenClassicsServer.common.CommonService;
import com.thirteenClassicsServer.mapper.PictureMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JdbPicCache {
    @Autowired
    private CommonService commonService;
    @Autowired
    private PictureMapper pictureMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Cacheable(value = "jdbPicForChapterCache", key = "'JdbContentForChapter-' + #jdbContentForChapterDTO.bookId + #jdbContentForChapterDTO.bookName + #jdbContentForChapterDTO.index")
    public List<PictureVO> jdbPicForChapter(JdbContentForChapterDTO jdbContentForChapterDTO){
        CatalogQueryDTO catalogQueryDTO = new CatalogQueryDTO();
        BeanUtils.copyProperties(jdbContentForChapterDTO, catalogQueryDTO);
        CatalogBook catalogBook = commonService.getMinorityCatalogBookByBookAndIndex(catalogQueryDTO);
        List<Picture> pictureList = pictureMapper.selectAllPictureByid(catalogBook.getId());
        return pictureList.stream()
                .map(picture -> new PictureVO(
                        picture.getId(),
                        picture.getPictureUrl(),
                        picture.getOrder()))
                .collect(Collectors.toList());
    }

    public List<PictureVO> getPicturesByCatalogBookId(Long catalogBookId) {
        String cacheKey = "catalog:book:pictures:" + catalogBookId;

        // 从缓存中读取数据
        String cachedPicturesJson = stringRedisTemplate.opsForValue().get(cacheKey);
        if (cachedPicturesJson != null) {
            try {
                // 将缓存中的 JSON 字符串反序列化为 List<Picture> 对象
                return objectMapper.readValue(cachedPicturesJson, objectMapper.getTypeFactory().constructCollectionType(List.class, PictureVO.class));
            } catch (Exception e) {
                // 处理反序列化异常
                e.printStackTrace();
            }
        }

        // 如果缓存中没有数据，则从数据库中查询
        List<PictureVO> picLists = pictureConvert(pictureMapper.selectAllPictureByid(catalogBookId));

        // 将查询结果存入缓存，转换为 JSON 字符串
        if (picLists != null) {
            try {
                String picturesJson = objectMapper.writeValueAsString(picLists);
                stringRedisTemplate.opsForValue().set(cacheKey, picturesJson, Duration.ofDays(7));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return picLists != null ? picLists : new ArrayList<>();
    }

    private List<PictureVO> pictureConvert(List<Picture> picLists) {
        return picLists.stream()
                .map(picture -> new PictureVO(
                        picture.getId(),
                        picture.getPictureUrl(),
                        picture.getOrder()))
                .collect(Collectors.toList());
    }
}
